/* sys */
#include "time.h"
#include "stdio.h"
/* user */
#include "rtc.h"
#include "main.h"

/* middlewares */



/* user parameters */
static uint16_t myrtc_time[] = {2025, 8, 8, 17, 05, 0};



/**
 * @brief rtc init
 * 
 */
void rtc_init(void)
{
    /* enable PMU and BKPI clocks */
    rcu_periph_clock_enable(RCU_BKPI);
    rcu_periph_clock_enable(RCU_PMU);

    /* allow access to BKP domain */
    pmu_backup_write_enable();
    /* reset backup domain */
    bkp_deinit();

    /* enable LXTAL */
    rcu_osci_on(RCU_LXTAL);
    /* wait till LXTAL is ready */
    rcu_osci_stab_wait(RCU_LXTAL);
    /* select RCU_LXTAL as RTC clock source */
    rcu_rtc_clock_config(RCU_RTCSRC_LXTAL);

    /* enable RTC Clock */
    rcu_periph_clock_enable(RCU_RTC);
    /* wait for RTC registers synchronization */
    rtc_register_sync_wait();
    /* wait until last write operation on RTC registers has finished */
    rtc_lwoff_wait();

    /* enable the RTC second interrupt*/
    rtc_interrupt_enable(RTC_INT_SECOND);
    // rtc_interrupt_enable(RTC_INT_ALARM);
    /* wait until last write operation on RTC registers has finished */
    rtc_lwoff_wait();

    /* set RTC prescaler: set RTC period to 1s */
    rtc_prescaler_set(32767);

    /* wait until last write operation on RTC registers has finished */
    rtc_lwoff_wait();
}

void rtc_settime(void)
{
	uint32_t time_cnt;			//time cnt
    struct tm time_data;

	time_data.tm_year = myrtc_time[0]-1900;
	time_data.tm_mon = myrtc_time[1]-1;
	time_data.tm_mday = myrtc_time[2];
	time_data.tm_hour = myrtc_time[3];
	time_data.tm_min = myrtc_time[4];
	time_data.tm_sec = myrtc_time[5];

    /* turn struct to cnt (s) */
    time_cnt = mktime(&time_data) - 8 * 60 * 60;

    /* use function to set time*/
    rtc_counter_set(time_cnt);
    /* wait until last write operation on RTC registers has finished */
    rtc_lwoff_wait();
}

/**
 * @brief rtc get now time -- YYYY-MM-DD HH:MM:SS
 * 
 * @return char* 
 */
void rtc_gettime(char* buffer)
{
    time_t timestamp = rtc_counter_get() + 28800;
    struct tm *time_info;  

    time_info = localtime(&timestamp);
    snprintf(buffer, 20, "%04d-%02d-%02d %02d:%02d:%02d",
            time_info->tm_year + 1900,
            time_info->tm_mon + 1,
            time_info->tm_mday,
            time_info->tm_hour,
            time_info->tm_min,
            time_info->tm_sec
            );
}


